<?php
require_once 'Groups.php';
require_once 'Banks.php';
require_once 'Clients.php';

class Admin_GroupController extends HTech_Controller_Action
{
    function init()
    {
        $cfg = array(
            'model' => 'Groups'
        );
        parent::init($cfg);    
    }
    
    public function addAction() 
    {
        /*
         * Do nothing, groups are added with admin.json.addGroup
         */
    }

    public function exportAction()
    {
        $id = (int) $this->getRequest()->getParam('id');
        try {
            $groupRecord = $this->_model->getRecord($id);  
        } catch (Exception $e) {
            $this->_helper->flashMessenger->addMessage($e->getMessage());
            $this->_redirect('/default/auth/deny'); 
        }        
        $this->_helper->layout->setLayout('form');
        $this->view->form = new Emms_Form_Admin_GroupExport($groupRecord);        
        if ($this->getRequest()->isPost()) {
            if ($this->view->form->isValid($this->getRequest()->getPost())) {
                $data = $this->view->form->getValues();
                $banks = new Banks();
                $bankRecordTo = $banks->getRecord($data['BankId']);
                if (count($bankRecordTo->r->groups) < Zend_Registry::get('HT_Config')->portfolio->group->max ) {  
                    $bankIdFrom = $groupRecord->d->BankId;
                    $groupRecord->d->BankId = $data['BankId'];
                    $groupRecord->d->LastEditUserId = Zend_Auth::getInstance()->getIdentity()->UserId;
                    $groupRecord->d->LastEditDate = date('Y-m-d H:i:s');
                    $groupRecord->d->save();
                    Banks::resetChildren($data['BankId']);
                    Banks::resetChildren($bankIdFrom);
                    Zend_Controller_Action_HelperBroker::getStaticHelper('flashMessenger')
                        ->addMessage(array('scs' => $this->view->translate("Operation successfully completed!")));
                    $this->_redirect(sprintf('/admin/bank/add/id/%s/group/%s', $groupRecord->d->BankId, $groupRecord->d->GroupId));
                    exit();
                } else {
                $this->view->form->setDescription($this->view->translate("Operation couldn't be completed. The selected bank has the maximum number of groups allowed."));
                }  
            }                
        } else {
            $this->view->form->setDefaults($groupRecord->d->toArray());  
        }  
        $this->view->group = $groupRecord;
    }
}
